/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.frontendproject.webservice;

import com.inspur.edp.web.common.entity.ResultCode;
import com.inspur.edp.web.common.entity.ResultMessage;
import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.jitruntimebuild.scriptcache.api.entity.ScriptCacheResponse;
import com.inspur.edp.web.jitruntimebuild.scriptcache.localserver.LocalServerVersionManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 零代码web服务
 *
 * @author guozhiqi
 */
public class ZeroCodeWebServiceImpl implements ZeroCodeWebService {

    @Override
    public ResultMessage  beforeNavigateLoadFile(String indexHtmlUrl, String routeUri, String options) {
        if (StringUtility.isNullOrEmpty(indexHtmlUrl)) {
            throw new RuntimeException("请设置默认首页参数");
        }
        if (StringUtility.isNullOrEmpty(routeUri)) {
            throw new RuntimeException("请设置路由参数");
        }
        // 调整成为/  形式
        String indexHtmlPath = FileUtility.getPlatformIndependentPath(indexHtmlUrl);
        String indexHtmlName = "index.html";
        if (!StringUtils.endsWith(indexHtmlPath, indexHtmlName)) {
            throw new RuntimeException("默认首页参数必须以index.html作为后缀，请修正！");
        }
        String projectPath = indexHtmlPath.substring(0, indexHtmlPath.length() - indexHtmlName.length());
        if (StringUtility.isNullOrEmpty(projectPath) || projectPath.equals("/")) {
            throw new RuntimeException("请设置正确的路径参数，例如：apps/scm/sd/sales/index.html");
        }

        String[] arrProjectPathSplit = projectPath.split("/");
        // 获取对应的工程名
        String projectName = arrProjectPathSplit[arrProjectPathSplit.length - 1];

        if (projectPath.endsWith("/")) {
            projectPath = projectPath.substring(0, projectPath.length() - 1);
        }
        if (projectPath.startsWith("/")) {
            projectPath = projectPath.substring(1);
        }
        ScriptCacheResponse scriptCacheResponse = LocalServerVersionManager.getSingleInstance().checkVersionWithProjectNameAndRelativePath(projectName, projectPath);
        if (!scriptCacheResponse.isSuccess()) {
            throw new RuntimeException(scriptCacheResponse.getErrorMessage());
        }

        // 执行路由跳转
        try {
            String indexHtml = indexHtmlPath.startsWith("/") ? indexHtmlPath.substring(1) : indexHtmlPath;
            // 判断html是否存在

            String redirectUrl = "/" + indexHtml + "#/" + routeUri;
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = servletRequestAttributes.getResponse();
            assert response != null;
            response.sendRedirect(redirectUrl);
        } catch (IOException e) {
            WebLogger.Instance.error(e);
        }

        // 进行页面跳转
        return ResultCode.success();
    }
}
